package cn.springcloud.fix.demo.thread;

public class ThreadTest1 {

    public static void main(String[] args) {
        //test1();
        //test2();
        test3();
    }

    private static void test1() {
        new Apple().start();
        new Apple().start();
        new Apple().start();
    }

    private static void test2() {
        Apple apple = new Apple();  //虽然三个线程   但是使用同一个apple引用
        new Thread(apple, "Thread-0").start();
        new Thread(apple, "Thread-1").start();
        new Thread(apple, "Thread-2").start();
    }

    private static void test3() {
        Apple2 apple = new Apple2();  //虽然三个线程   但是使用同一个apple引用
        new Thread(apple, "Thread-0").start();
        new Thread(apple, "Thread-1").start();
        new Thread(apple, "Thread-2").start();
    }

    static class Apple extends Thread {
        private int num = 10;

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + "吃了编号为      " + (num--) + "   的苹果");
                }
            }
        }
    }

    static class Apple2 extends Thread {
        private int num = 10;

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (this) {
                    if (num > 0) {
                        System.out.println(Thread.currentThread().getName() + "吃了编号为      " + (num--) + "   的苹果");
                    }
                }
            }
        }
    }
}



